package com.activemq.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2018/10/24
 * @Description: 消息配置
 **/
@Configuration
@EnableJms
public class ActiveMQConfig {
    /**
     * @Author: 胡成
     * @Date:   2018/10/24 11:59
     * @Description: 点对点
    **/
    @Bean
    public Queue queue(){
        return new ActiveMQQueue("study.msg.queue");
    }

    @Bean
    public Topic topic(){
        return new ActiveMQTopic("study.msg.topic");
    }

    @Bean
    public Topic topic2(){
        return new ActiveMQTopic("study.msg.topic2");
    }

    /**
     * JmsListener注解默认只接收queue消息,如果要接收topic消息,需要设置containerFactory
     */
    @Bean
    public JmsListenerContainerFactory<?> topicListenerContainer(ConnectionFactory activeMQConnectionFactory) {
        DefaultJmsListenerContainerFactory topicListenerContainer = new DefaultJmsListenerContainerFactory();
        topicListenerContainer.setPubSubDomain(true);
        topicListenerContainer.setConnectionFactory(activeMQConnectionFactory);
        return topicListenerContainer;
    }

    @Autowired
    private ActiveMQConnectionFactory connectionFactory;

    //订阅持久化，必须有factory.setSubscriptionDurable(true); 和factory.setClientId("id1");
    @Bean(name = "topicListenerFactory1")
    public DefaultJmsListenerContainerFactory topicListenerFactory1(){
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(true);
        factory.setSubscriptionDurable(true);
        factory.setClientId("id1");
        return factory;
    }

}
